﻿using FluentData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.tanlingyun;
using com.tanlingyun.ViewModel;
using com.tanlingyun.baojia.Entity;

namespace com.tanlingyun.DbServices
{
    public class BaseService
    {
        protected FluentData.IDbContext db;

        public BaseService()
        {
            db = new FluentData.DbContext().ConnectionStringName("MySqlConnection2", new FluentData.MySqlProvider()).IgnoreIfAutoMapFails(true);
        }

        ~BaseService()
        {

        }

        ///// <summary>
        ///// 添加日志
        ///// </summary>
        ///// <param name="log"></param>
        ///// <returns></returns>
        //public int AddLog(Entity.Logs log)
        //{
        //    return db.Insert<Entity.Logs>("Logs", log).AutoMap(x => x.ID).Execute();
        //}

        /// <summary>
        /// 通用分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="PageInfo"></param>
        /// <returns></returns>
        public ViewModel.PageInfo<T> GetPageInfo<T>(ViewModel.PageInfo<T> PageInfo)
        {
            try
            {
                string sqlcount = string.Format("select count(1) from {0} ", PageInfo.TableName);
                if (!string.IsNullOrEmpty(PageInfo.Where)) { sqlcount += string.Format("where {0}", PageInfo.Where); }
                PageInfo.TotalCount = db.Sql(sqlcount).QuerySingle<int>();

                if (PageInfo.PageSize <= 0) { PageInfo.PageSize = 10; }

                PageInfo.TotalPage = (PageInfo.TotalCount % PageInfo.PageSize == 0) ? PageInfo.TotalCount / PageInfo.PageSize : PageInfo.TotalPage = PageInfo.TotalCount / PageInfo.PageSize + 1;

                //基本查询
                ISelectBuilder<T> building = db.Select<T>(PageInfo.Fields).From(PageInfo.TableName);

                //条件
                if (!string.IsNullOrEmpty(PageInfo.Where))
                {
                    building = building.Where(PageInfo.Where);
                }

                //分组
                if (!string.IsNullOrEmpty(PageInfo.GroupBy))
                {
                    building = building.GroupBy(PageInfo.GroupBy);
                }

                //过滤
                if (!string.IsNullOrEmpty(PageInfo.Having))
                {
                    building = building.Having(PageInfo.Having);
                }

                //排序
                if (!string.IsNullOrEmpty(PageInfo.OrderBy))
                {
                    building = building.OrderBy(PageInfo.OrderBy);
                }

                //分页
                PageInfo.List = building.Paging(PageInfo.PageIndex, PageInfo.PageSize).QueryMany();
                return PageInfo;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 获取数据库连接信息
        /// </summary>
        protected V_DBInfo GetDbInfo
        {
            get
            {
                if(db!=null && db.Data != null && !string.IsNullOrWhiteSpace(db.Data.ConnectionString))
                {
                    string[] allprop = db.Data.ConnectionString.Split(';').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
                    if(allprop!=null && allprop.Length>0)
                    {
                        V_DBInfo info = new V_DBInfo();
                        //获取数据库地址
                        string server = allprop.Where(x => (x.Split('=')[0].ToLower().Equals("server"))).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(server) && server.LastIndexOf("=") + 1 < server.Length)
                        {
                            info.Host = server.Split('=')[1];
                        }
                        else return null;
                        //获取数据库端口
                        string port = allprop.Where(x => (x.Split('=')[0].ToLower().Equals("port"))).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(port) && port.LastIndexOf("=") + 1 < port.Length)
                        {
                            info.Port = port.Split('=')[1];
                        }
                        else return null;
                        //获取数据库用户名
                        string userid = allprop.Where(x => (x.Split('=')[0].ToLower().Equals("user id"))).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(userid) && userid.LastIndexOf("=") + 1 < userid.Length)
                        {
                            info.UserID = userid.Split('=')[1];
                        }
                        else return null;
                        //获取密码
                        string password = allprop.Where(x => (x.Split('=')[0].ToLower().Equals("password"))).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(password) && password.LastIndexOf("=") + 1 < password.Length)
                        {
                            info.Password = password.Split('=')[1];
                        }
                        else info.Password = "";
                        return info;
                    }
                }
                return null;
            }    
        }

        public int AddLog(Log log)
        {
            return db.Insert<Log>("Log", log).AutoMap(x => x.ID).Execute();
        }

    }
}
